#!/bin/bash

# SmartInput 服务状态检查脚本
# 检查所有服务的运行状态

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# PID文件路径
PIDS_DIR="$PROJECT_ROOT/.pids"
SERVER_PID_FILE="$PIDS_DIR/server.pid"
MOBILE_PID_FILE="$PIDS_DIR/mobile.pid"
ADMIN_PID_FILE="$PIDS_DIR/admin.pid"

# 日志文件路径
LOGS_DIR="$PROJECT_ROOT/logs"
SERVER_LOG="$LOGS_DIR/server.log"
MOBILE_LOG="$LOGS_DIR/mobile.log"
ADMIN_LOG="$LOGS_DIR/admin.log"

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查端口状态
check_port_status() {
    local port=$1
    local service_name=$2
    
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        local pid=$(lsof -ti :$port 2>/dev/null | head -1)
        print_message $GREEN "   ✅ $service_name 运行中 (端口 $port, PID: $pid)"
        return 0
    else
        print_message $RED "   ❌ $service_name 未运行 (端口 $port)"
        return 1
    fi
}

# 检查进程状态
check_process_status() {
    local pid_file=$1
    local service_name=$2
    
    if [ ! -f "$pid_file" ]; then
        print_message $RED "   ❌ $service_name PID文件不存在"
        return 1
    fi
    
    local pid=$(cat "$pid_file")
    
    if [ -z "$pid" ]; then
        print_message $RED "   ❌ $service_name PID文件为空"
        return 1
    fi
    
    if kill -0 "$pid" 2>/dev/null; then
        # 获取进程信息
        local process_info=$(ps -p "$pid" -o pid,ppid,etime,cmd --no-headers 2>/dev/null || echo "")
        if [ -n "$process_info" ]; then
            print_message $GREEN "   ✅ $service_name 运行中 (PID: $pid)"
            print_message $CYAN "      进程信息: $process_info"
        else
            print_message $YELLOW "   ⚠️  $service_name PID存在但无法获取进程信息"
        fi
        return 0
    else
        print_message $RED "   ❌ $service_name 进程不存在 (PID: $pid)"
        return 1
    fi
}

# 检查日志文件
check_log_status() {
    local log_file=$1
    local service_name=$2
    
    if [ -f "$log_file" ]; then
        local log_size=$(du -h "$log_file" | cut -f1)
        local last_modified=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$log_file" 2>/dev/null || stat -c "%y" "$log_file" 2>/dev/null | cut -d'.' -f1)
        print_message $BLUE "   📄 $service_name 日志: $log_file ($log_size)"
        print_message $CYAN "      最后修改: $last_modified"
        
        # 显示最后几行日志
        print_message $CYAN "      最新日志:"
        tail -3 "$log_file" 2>/dev/null | while IFS= read -r line; do
            print_message $CYAN "        $line"
        done
    else
        print_message $YELLOW "   ⚠️  $service_name 日志文件不存在: $log_file"
    fi
}

# 检查网络连接
check_network_status() {
    print_message $BLUE "🌐 网络连接状态:"
    
    # 检查WebSocket服务器连接
    if curl -s --connect-timeout 3 http://localhost:3001 >/dev/null 2>&1; then
        print_message $GREEN "   ✅ WebSocket服务器可访问 (http://localhost:3001)"
    else
        print_message $RED "   ❌ WebSocket服务器不可访问"
    fi
    
    # 检查管理后台连接
    if curl -s --connect-timeout 3 -k https://localhost:3002 >/dev/null 2>&1; then
        print_message $GREEN "   ✅ 管理后台可访问 (https://localhost:3002)"
    else
        print_message $RED "   ❌ 管理后台不可访问"
    fi
    
    # 检查移动端应用连接
    local mobile_ports=(3000 3002 3003 3004 3005)
    local mobile_found=false
    
    for port in "${mobile_ports[@]}"; do
        if curl -s --connect-timeout 1 http://localhost:$port >/dev/null 2>&1; then
            print_message $GREEN "   ✅ 移动端应用可访问 (http://localhost:$port)"
            mobile_found=true
            break
        fi
    done
    
    if [ "$mobile_found" = false ]; then
        print_message $RED "   ❌ 移动端应用不可访问"
    fi
}

# 显示系统资源使用情况
show_resource_usage() {
    print_message $BLUE "💻 系统资源使用:"
    
    # CPU和内存使用情况
    if command -v top >/dev/null 2>&1; then
        local cpu_usage=$(top -l 1 -n 0 | grep "CPU usage" | awk '{print $3}' 2>/dev/null || echo "N/A")
        print_message $CYAN "   CPU使用率: $cpu_usage"
    fi
    
    # 内存使用情况
    if command -v free >/dev/null 2>&1; then
        local mem_info=$(free -h | grep "Mem:" | awk '{print "已用: "$3" / 总计: "$2}' 2>/dev/null || echo "N/A")
        print_message $CYAN "   内存使用: $mem_info"
    elif command -v vm_stat >/dev/null 2>&1; then
        local mem_info=$(vm_stat | head -4 | tail -3 | tr '\n' ' ' 2>/dev/null || echo "N/A")
        print_message $CYAN "   内存状态: $mem_info"
    fi
    
    # 磁盘使用情况
    local disk_usage=$(df -h . | tail -1 | awk '{print "已用: "$3" / 总计: "$2" ("$5")"}' 2>/dev/null || echo "N/A")
    print_message $CYAN "   磁盘使用: $disk_usage"
}

# 检查 SSL 证书状态
check_ssl_status() {
    print_message $BLUE "🔒 SSL 证书状态:"
    
    local cert_path="$PROJECT_ROOT/certs/cert.pem"
    local key_path="$PROJECT_ROOT/certs/key.pem"
    
    if [ -f "$cert_path" ] && [ -f "$key_path" ]; then
        print_message $GREEN "   ✅ SSL 证书文件存在"
        
        # 检查证书有效性
        if openssl x509 -in "$cert_path" -checkend 0 >/dev/null 2>&1; then
            print_message $GREEN "   ✅ 证书有效"
            local expiry=$(openssl x509 -in "$cert_path" -enddate -noout | cut -d= -f2)
            print_message $CYAN "   📅 过期时间: $expiry"
        else
            print_message $RED "   ❌ 证书已过期或无效"
        fi
    else
        print_message $RED "   ❌ SSL 证书文件不存在"
    fi
}

# 主函数
main() {
    print_message $GREEN "📊 SmartInput 服务状态检查"
    print_message $BLUE "================================"
    
    # 检查WebSocket服务器状态
    print_message $BLUE "🖥️  WebSocket服务器状态:"
    check_process_status "$SERVER_PID_FILE" "WebSocket服务器"
    check_port_status 3001 "WebSocket服务器"
    check_log_status "$SERVER_LOG" "WebSocket服务器"
    
    print_message $BLUE ""
    
    # 检查管理后台应用状态
    print_message $BLUE "🛠️  管理后台应用状态:"
    check_process_status "$ADMIN_PID_FILE" "管理后台应用"
    check_port_status 3002 "管理后台应用"
    check_log_status "$ADMIN_LOG" "管理后台应用"
    
    print_message $BLUE ""
    
    # 检查移动端应用状态
    print_message $BLUE "📱 移动端应用状态:"
    check_process_status "$MOBILE_PID_FILE" "移动端应用"
    
    # 检查常用端口
    local mobile_running=false
    for port in 3000 3002 3003 3004 3005; do
        if check_port_status $port "移动端应用"; then
            mobile_running=true
            break
        fi
    done
    
    if [ "$mobile_running" = false ]; then
        print_message $RED "   ❌ 移动端应用未在常用端口运行"
    fi
    
    check_log_status "$MOBILE_LOG" "移动端应用"
    
    print_message $BLUE ""
    
    # 检查网络连接
    check_network_status
    
    print_message $BLUE ""
    
    # 显示系统资源使用情况
    show_resource_usage
    
    print_message $BLUE ""
    
    # 检查 SSL 证书状态
    check_ssl_status
    
    print_message $BLUE ""
    print_message $BLUE "================================"
    
    # 总结状态
    local server_running=false
    local mobile_running=false
    local admin_running=false
    
    if lsof -Pi :3001 -sTCP:LISTEN -t >/dev/null 2>&1; then
        server_running=true
    fi
    
    if curl -s --connect-timeout 1 -k https://localhost:3002 >/dev/null 2>&1; then
        admin_running=true
    fi
    
    for port in 3000 3002 3003 3004 3005; do
        if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
            mobile_running=true
            break
        fi
    done
    
    if [ "$server_running" = true ] && [ "$mobile_running" = true ] && [ "$admin_running" = true ]; then
        print_message $GREEN "🎉 所有服务运行正常！"
    elif [ "$server_running" = true ] && [ "$admin_running" = true ]; then
        print_message $YELLOW "⚠️  WebSocket服务器和管理后台运行中"
    elif [ "$server_running" = true ]; then
        print_message $YELLOW "⚠️  仅WebSocket服务器运行中"
    elif [ "$mobile_running" = true ]; then
        print_message $YELLOW "⚠️  仅移动端应用运行中"
    else
        print_message $RED "❌ 所有服务都未运行"
    fi
    
    print_message $BLUE ""
    print_message $BLUE "🛠️  管理命令:"
    print_message $BLUE "   启动服务: ./start.sh"
    print_message $BLUE "   停止服务: ./stop.sh"
    print_message $BLUE "   重启服务: ./restart.sh"
}

# 执行主函数
main "$@"
